package cn.dinkevin.xui.thread;

import android.os.Looper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.dinkevin.xui.util.HandlerUtil;

/**
 * 线程工具类
 * @author chengpengfei
 */
public class ThreadExecutor {

	private ThreadExecutor() {}
	/**
	 * 定义线程池线程数量
	 */
	public static final int MAX_THREAD_COUNT = 15;
	
	/**
	 * 声明线程池,默认最多只能有 7 个线程同时执行
	 */
	private static final ExecutorService threadPool = Executors.newFixedThreadPool(MAX_THREAD_COUNT);

	/**
	 * 判断是否在主线程
	 * 
	 * @return
	 */
	public static boolean isOnMainThread() {
		return Looper.myLooper() == Looper.getMainLooper();
	}

	/**
	 * Throws an {@link IllegalArgumentException} if called on a
	 * thread other than the main thread.
	 */
	public static void assertMainThread() {
		if (!isOnMainThread()) {
			throw new IllegalArgumentException("You must call this method on the main thread");
		}
	}

	/**
	 * Throws an {@link IllegalArgumentException} if called on the
	 * main thread.
	 */
	public static void assertBackgroundThread() {
		if (!isOnBackgroundThread()) {
			throw new IllegalArgumentException("YOu must call this method on a background thread");
		}
	}

	/**
	 * Returns {@code true} if called on the main thread, {@code false}
	 * otherwise.
	 */
	public static boolean isOnBackgroundThread() {
		return !isOnMainThread();
	}
	
	/**
	 * 在主线程执行此代码片断
	 * @param runnable
	 * @return true -> 添加成功；false -> 添加失败
	 */
	public static boolean main(Runnable runnable){
		if(isOnMainThread()){
			runnable.run();
			return true;
		}else{
			return HandlerUtil.getInstance().post(runnable);
		}
	}
	
	/**
	 * 在主线程执行此代码片断，在指定延时间后执行
	 * @param runnable
	 * @param delay 延时时间 大于 0
	 * @return true -> 添加成功；false -> 添加失败
	 */
	public static boolean main(Runnable runnable, long delay){
		if(delay < 1) return false;
		return HandlerUtil.getInstance().postDelayed(runnable,delay);
	}
	
	/**
	 * 添加到线程池中执行
	 * @param runnable
	 * @return true -> 添加成功；false -> 添加失败
	 */
	public static boolean pool(Runnable runnable){
		if(threadPool.isShutdown()) return false;
		threadPool.execute(runnable);
		return true;
	}

	/**
	 * 在应用线程池中运行一个任务
	 * @param runnable
	 * @param delayTime
	 * @return
	 */
	public static boolean pool(final Runnable runnable, final long delayTime){

		if(delayTime < 0) return false;
		Runnable task = new Runnable() {
			@Override
			public void run() {
				sleep(delayTime);
				runnable.run();
			}
		};
		return pool(task);
	}

	/**
	 * 在当前线程中暂停
	 * @param time
     */
	public static void sleep(long time){
		try {
			Thread.sleep(time);
		}catch (Exception e){

		}
	}
	
	/**
	 * 此接口调用的时候要慎重，关闭线程池后，则无法正常调用 {@link #pool(Runnable)}
	 */
	public static void shutdown(){
		threadPool.shutdown();
	}
}
